/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useRef } from 'react';
import { message, Button } from 'antd';
import ProForm, {
  ModalForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormList,
  ProFormRadio,
  ProFormDependency,
  ProFormDateTimePicker,
} from '@ant-design/pro-form';
import normalize from '@/utils/rules';
import ProCard from '@ant-design/pro-card';
import {
  lottery_platform,
  lottery_type,
  lotteryLevel,
  publishType,
} from '@/components/_pages/ad/utils/ad.lottery';
import type { ProFormInstance } from '@ant-design/pro-form';
import { lotteryEdit } from '@/services/ad/lottery';
import KbPreviewModal from '@/components/_pages/ad/lottery/publish/components/KbPreviewModal';
import moment from 'moment';
import styles from './index.less';
import { debounce } from 'lodash';
import UploadWithCrypto from '@base/components/upload-width-crypto';

interface IndexPorps {
  record?: any;
  children: any;
  actionRef: any;
}

const Index = (props: IndexPorps) => {
  const { record = {}, children, actionRef } = props;
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [preData, setPreData] = useState({});
  const { id = '', ad_url = '', status } = record;
  const [filesList, setFilesList] = useState<any[]>([]);

  const uploadButton = (
    <div style={{ color: '#4ca4f8' }}>
      <div style={{ marginTop: 8 }}>点击上传素材</div>
    </div>
  );
  const onSuccess = (data: any) => setFilesList([...filesList, { url: data.data }]);

  const handleChange = (file: any) => {
    const { fileList } = file;
    if (filesList.length > fileList.length) {
      setFilesList(fileList);
    }
  };

  const handlePreview = () => {
    formRef.current?.validateFields().then((res) => {
      const { lottery_time: time, ...rest } = res;
      const url = filesList[0]?.url;
      const lottery_time = moment(time).format('YYYY-MM-DD HH:mm:ss');
      setPreData({ ...rest, lottery_time, ad_url: url });
      setVisible(true);
    });
  };

  const onCloseModal = () => setVisible(false);

  const disabledDate = (current: any) => {
    return current && current < moment().subtract('days');
  };

  useEffect(() => {
    if (ad_url) {
      setFilesList([{ url: ad_url }]);
    } else {
      setFilesList([]);
    }
  }, [ad_url]);
  const onFinish = async () => true;
  const handleOk = debounce((type: string) => {
    formRef.current?.validateFields().then(async (values) => {
      const { publish = false, prize_param: params = [], lottery_time: time, ...rest } = values;
      const lottery_time = moment(time).format('YYYY-MM-DD HH:mm:ss');
      delete rest.publish;

      const url = filesList[0]?.url;
      const prize_param = params.map((item: any, index: number) => {
        const { prize_type, page: itemUrl = '', money = 0, half_open = false } = item;
        const ranking = index + 1;
        item.ranking = ranking;
        // money 兼容后端字段
        item.money = money;
        if (prize_type === 'url') {
          const [page, appid] = itemUrl.split(',');
          delete item.page;
          delete item.half_open;
          return {
            ...item,
            page,
            appid,
            money,
            half_open,
          };
        } else {
          return item;
        }
      });
      const queryData = {
        ...rest,
        lottery_time,
        publish: publish ? '1' : '0',
        prize_param: JSON.stringify(prize_param),
      };
      if (type == 'save') queryData.id = id;
      if (url) queryData.ad_url = url;
      const { code, msg } = await lotteryEdit(queryData);
      if (code == 0) {
        setFilesList([]);
        message.success('操作成功');
        actionRef.current?.reload();
        formRef.current?.submit();
      } else {
        message.error(msg);
      }
    });
  }, 300);
  const formatRowData = (data: any, callback: Function) => {
    const { prize_type } = data;
    if (prize_type !== 'money') {
      delete data.money;
    }
    if (prize_type !== 'url') {
      delete data.page;
      delete data.half_open;
    }
    callback(data);
  };
  return (
    <ModalForm
      title={`${id ? '编辑抽奖' : '发布新抽奖'}`}
      className={styles.publishModal}
      formRef={formRef}
      initialValues={{
        type: '0',
        ...record,
      }}
      width={800}
      trigger={children}
      labelCol={{ span: 4 }}
      modalProps={{
        destroyOnClose: true,
        bodyStyle: {
          height: 600,
          overflow: 'scroll',
        },
      }}
      submitter={{
        render: () => {
          return [
            <Button type='primary' onClick={handlePreview} key='preview'>
              生成预览
            </Button>,
            <Button
              type='primary'
              key='save'
              disabled={`${status}` === '1'}
              onClick={handleOk.bind(null, 'save')}
            >
              保存
            </Button>,
            id && (
              <Button type='primary' key='copy' onClick={handleOk.bind(null, 'copy')}>
                复制
              </Button>
            ),
          ];
        },
      }}
      layout='horizontal'
      onFinish={onFinish}
    >
      <ProFormCheckbox name='publish' label='开放状态'>
        公开
      </ProFormCheckbox>
      <ProFormDigit
        name='rank'
        min={1}
        fieldProps={{ precision: 0 }}
        label='展示顺序'
        rules={[{ required: true, message: '请输入展示顺序' }]}
      />
      <ProFormSelect
        name='platform'
        valueEnum={lottery_platform}
        label='发布平台'
        rules={[{ required: true, message: '请选择发布平台' }]}
      />
      <ProFormText
        name='name'
        label='抽奖名称'
        normalize={normalize.bind(null, 'Emoji', '')}
        rules={[{ required: true, message: '请输入抽奖名称' }]}
      />
      <ProForm.Item
        label='广告区域图片'
        name='ad_url'
        rules={[{ required: true, message: '请上传素材' }]}
      >
        <UploadWithCrypto
          action='/Inn/uploadWuLiao'
          listType='picture-card'
          accept='.jpg,.png'
          multiple={false}
          fileList={filesList}
          onChange={handleChange}
          onSuccess={onSuccess}
          showUploadList={{ showPreviewIcon: false }}
        >
          {filesList.length >= 1 ? null : uploadButton}
        </UploadWithCrypto>
      </ProForm.Item>
      <ProFormRadio.Group
        label='抽奖类型'
        name='lottery_type'
        radioType='button'
        valueEnum={lottery_type}
        rules={[{ required: true, message: '请选择抽奖类型' }]}
      />
      <ProFormDependency name={['lottery_type']}>
        {({ lottery_type: type }) => {
          return (
            <>
              {type === '1' ? (
                <ProFormDigit
                  label='中奖概率'
                  name='odds'
                  min={1}
                  max={100}
                  fieldProps={{ precision: 0 }}
                  addonAfter='%'
                  rules={[{ required: true, message: '请输入奖品几率' }]}
                />
              ) : null}
              <ProFormDateTimePicker
                label={`${type === '0' ? '开奖' : '结束'}时间`}
                name='lottery_time'
                fieldProps={{ showTime: true, disabledDate }}
                rules={[{ required: true, message: '请选择开奖时间' }]}
              />
            </>
          );
        }}
      </ProFormDependency>
      <ProFormTextArea
        name='desc'
        label='抽奖说明'
        normalize={normalize.bind(null, 'Emoji', '')}
        rules={[{ required: true, message: '请输入抽奖说明' }]}
      />
      <ProFormList
        name='prize_param'
        label='奖品设置'
        min={1}
        max={10}
        copyIconProps={false}
        itemContainerRender={(doms) => {
          return <ProCard bordered>{doms}</ProCard>;
        }}
      >
        {(f, index, { getCurrentRowData, setCurrentRowData }) => {
          return (
            <ProForm.Group>
              <ProFormText
                label={`${lotteryLevel[index]}等奖名称`}
                name='name'
                normalize={normalize.bind(null, 'Emoji', '')}
                rules={[{ required: true, message: '请输入奖品名称' }]}
              />
              <ProFormDigit
                label='奖品数量'
                name='number'
                min={0}
                addonAfter='份'
                rules={[{ required: true, message: '请输入奖品数量' }]}
              />
              <ProFormRadio.Group
                label='发奖类型选择'
                name='prize_type'
                radioType='button'
                initialValue='money'
                valueEnum={publishType}
                fieldProps={{
                  onChange: () => formatRowData(getCurrentRowData(), setCurrentRowData),
                }}
              />
              <ProFormDependency name={['prize_type']}>
                {({ prize_type }) =>
                  prize_type === 'money' ? (
                    <ProFormDigit
                      name='money'
                      min={0}
                      max={100}
                      fieldProps={{ precision: 2 }}
                      addonAfter='元/份'
                      rules={[{ required: true, message: '请输入金额' }]}
                    />
                  ) : prize_type === 'url' ? (
                    <ProForm.Group>
                      <ProFormText
                        name='page'
                        normalize={normalize.bind(null, 'Emoji', '')}
                        rules={[{ required: true, message: '请输入链接' }]}
                      />
                      <ProFormCheckbox name='half_open'>小程序半屏幕打开</ProFormCheckbox>
                    </ProForm.Group>
                  ) : null
                }
              </ProFormDependency>
            </ProForm.Group>
          );
        }}
      </ProFormList>
      <KbPreviewModal visible={visible} preData={preData} onVisibleChange={onCloseModal} />
    </ModalForm>
  );
};

export default Index;
